'use strict';

const axios = require('axios');
const urlJoin = require('url-join');
const semver = require('semver');

/** 获取npm信息 */
function getNpmInfo(packageName, registry) {
  if (!packageName) {
    return null;
  }
  const registryUrl = registry || getDefaultRegistry(true);
  const npmInfoUrl = urlJoin(registryUrl, packageName);
  return axios
    .get(npmInfoUrl)
    .then((response) => {
      if (response.status === 200) {
        return response.data;
      } else {
        return null;
      }
    })
    .catch((err) => {
      return Promise.reject(err);
    });
}

/** 获取默认源 */
function getDefaultRegistry(isOrigin = false) {
  return isOrigin
    ? 'https://registry.npmjs.org'
    : 'https://registry.npm.taobao.org';
}

/** 获取包所有的线上版本 */
async function getNpmVersions(packageName, registry) {
  const data = await getNpmInfo(packageName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return [];
  }
}

/** 获取所有超过baseVersion的版本号 */
function getSemverVersions(baseVersion, versions) {
  return versions
    .filter((version) => semver.satisfies(version, `^${baseVersion}`))
    .sort((a, b) => {
      return semver.gt(b, a) ? 1 : -1;
    });
}

/** 获取npm线上最新的版本号 */
async function getNpmSemverVersion(baseVersion, packageName, registry) {
  const versions = await getNpmVersions(packageName, registry);
  const newVersions = getSemverVersions(baseVersion, versions);
  if (newVersions && newVersions.length > 0) {
    return newVersions[0];
  }
}

/** 获取npm包最新版本 */
async function getNpmLatestVersion(npmName, registry) {
  const version = await getNpmVersions(npmName, registry);
  if (version && version.length > 0) {
    version.sort((a, b) => (semver.gt(b, a) ? 1 : -1));
    return version[0];
  } else {
    return null;
  }
}

module.exports = {
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersion,
  getDefaultRegistry,
  getNpmLatestVersion
};
